<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends CommonController{
	//个人主页与最新提问
	public function Userhome($table = ''){
		if(empty($_GET)){
			$this->error('非法访问',U('home/index/index'));
		}

		$id = $_GET['uid'];
		$result = M('user')->where("id = {$id}")->select();
		//得到用户所活跃的标签的对应的数量（提问)
		$questionTagNumSql = "select count(t1.id) count,t3.cname,t3.id as cid from question t1 LEFT JOIN category_question t2 on t1.id=t2.qid LEFT JOIN category t3 on t2.cid=t3.id where t1.uid={$id} group by t3.cname;";
		$questionTagNumRes = M()->query($questionTagNumSql);

		// 得到用户所活跃的标签的对应的数量（回答）
		$answersTagNumSql = "select count(t4.id) count,t3.cname,t3.id as cid from answer t4 LEFT JOIN  question t1 on t4.qid=t1.id LEFT JOIN category_question t2 on t1.id=t2.qid LEFT JOIN category t3 on t2.cid=t3.id where t4.uid='1' group by t3.cname";
		$answersTagNumRes = M()->query($answersTagNumSql);

		$tempArr = array();    //中间数组  把类名作为键 重组一个新数组 
		foreach ($answersTagNumRes as $key => $value) {
			$tempArr[$value['cname']]= $value;
		}

		//遍历$questionTagNumRes数组 判断当前数组的键是否存在中间数组$tempArr  有的话则将标签的count相加 否则的话就追加
		foreach ($questionTagNumRes as $k => $v) {
			if(isset($tempArr[$v['cname']])){
				$tempArr[$v['cname']]['count'] += $v['count'];
			}else{
				$tempArr[$v['cname']] = $v;
			}
		}

		//提问的
		if( $table == '' ){
			$count = M()->query("select count(id) count from question where uid = {$id} ")[0]['count']; // 获得数据总数SQL
			$Page       = new \Think\Page($count,3);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show       = $Page->show();// 分页显示输出
			$questionSql =  "select *from question where uid = {$id} order by create_time desc limit {$Page->firstRow},{$Page->listRows}";
			$questionRes = M()->query($questionSql);
		// 回答的.
		}else{
			$count = M()->query("select count(id) count from answer where uid = {$id} ")[0]['count']; // 获得数据总数
			$Page       = new \Think\Page($count,3);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show       = $Page->show();// 分页显示输出
			$questionSql =  "select t1.*, t2.id as qid,t2.content as acontent,t2.vote_num as avote_num from question t1 left join answer t2 on t1.id = t2.qid  where t2.uid = {$id} order by t2.create_time desc limit {$Page->firstRow},{$Page->listRows}";
			$questionRes = M()->query($questionSql);
			
		} 
		
		$this->assign('questionRes',$questionRes);
		$this->assign('endTagsRes',$tempArr);
		$this->assign('userdata',$result);
		$this->assign('Page',$show);  //渲染分页
		$this->display('user/userhome');
	}

	//获取到最新的回答
	public function newAnswer(){
		$this->Userhome('answer');
	}

	public function Userinfo(){
		
    	$maninfo = M('user')->find($_SESSION['uid']);

    	$this->assign('maninfo',$maninfo);

		$this->display();
	}

	public function update(){

		$table = M('user');
		$data = $table->create();

		if($table->save() !== false){
			$this->success('保存完成',U('Home/User/Userinfo'));
		}else{
			$this->error('保存失败');
		}

	}

	//展示头像上传页面
	public function faceupload(){

		$this->display();

	}

	//头像保存
	public function facesave(){
		$upload = new \Think\Upload();// 实例化上传类
	    $upload->maxSize   =     3145728 ;// 设置附件上传大小
	    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	    $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
	    $upload->savePath  =     'images/'; // 设置附件上传（子）目录
	    $info   =   $upload->upload();

	    if(!$info) {              			// 上传错误提示错误信息
	    	$returnMsg = array(
	    		'error'     => 1,
	    		'message'   => $upload->getError(),
	    		'file_path' => '',
    		);
	    }else{
	    	
	    	//上传成功拼接返回的路径及文件名 并且修改用户的头像
	    	foreach ($info as $key => $value) {
		    	$file_save_path = 'Uploads/'.$value['savepath'].'/'.$value['savename'];
		    }

		    //修改用户头像
		    $this->updateface($file_save_path);

	        $returnMsg = array(
	    		'error'    => 0,
	    		'message'  => '上传成功',
	    		'file_path' => __ROOT__.'/'.$file_save_path,
    		);
	    }
	    //上传成功 就ajax返回对应的信息
	    $this->ajaxReturn($returnMsg);
	}

	//更新头像方法
	public function updateface($file_path){
        $sql = "update user set face='{$file_path}' where id='{$_SESSION['uid']}' ";
        //如果成功删除 则返回true 并且删除之前的头像 
        // 判断是否有头像
        if(isset($_SESSION['face'])){
        	unlink($_SESSION['face']);
        	$_SESSION['face'] = $file_path; //重新将头像路径赋值给session
        	M()->execute($sql);
        	return true;
        }elseif(M()->execute($sql)){   //没有头像则直接执行更新语句 不需要删除原来的头像
        	return true;
        }
        return false;

	}

	public function useremail(){
		$this->display();
	}

	//检测要修改的邮箱
	public function checkemail(){
		$emailPreg = '/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i';

    	//判断邮箱格式是否符合要求
    	if(!preg_match($emailPreg, $_POST['emailvalue'])){
			$returnMsg = array(
				'error'     => 1,
				'content'   => '格式不正确',
			);  
			 		
    	}else{
    		$newemail =  M('user')->where("email = '{$_POST['emailvalue']}'")->getField('email');
    		$sql = "select * from user where email = '{$_POST['emailvalue']}'";
    		$num = count(M()->query($sql));

    		if( $num == 1 ){
    			//检测POST过来的
    			if( $newemail == $_SESSION['email']){
    				$returnMsg = array(
						'error'     => 1,
						'content'   => '不能使用您当前的邮箱',
					);
    			}
    			else{
    				$returnMsg = array(
						'error'     => 1,
						'content'   => '邮箱已经存在了',
					);
    			}
    			
    		}elseif( $num == 0 ){
    			$returnMsg = array(
					'error'     => 0,
					'content'   => '邮箱可用',
				);
    		}
    		
    	}
    	
    	$this->ajaxReturn($returnMsg);
	}

	//邮箱更改保存
	public function save_emai(){
		if(IS_POST){
			$table = M('user');
			$sql = "update user set email='{$_POST['email']}' where id = {$_SESSION['uid']} ";
			if($table->execute($sql)){
				session(null);
				$this->success('保存完成,请从新登陆',U('Home/register/register'));
			}else{
				$this->error('保存失败');
			}
		}
	}

	//密码修改页面 
	public function userpassword(){
		$this->display();
	}

	public function editpassword(){
		if(IS_POST){
			// 123456   
			$currentpwd = M('user')->where("id = {$_SESSION['uid']}")->getField('password');
			
			if( $currentpwd != $_POST['password'] || $_POST['confirmPassword'] != $_POST['newPassword'] ){
				$this->error('新密码有误');
			}else{
				$sql = "update user set password='{$_POST['confirmPassword']}' where id = {$_SESSION['uid']} ";
				if(M()->execute($sql)){
					session(null);
					$this->success('密码修改成功,重新登录',U('home/register/register'));
				}
			}
		}
	}

	//异步的都数据的方法 调用下面三个的方法
    public function GetThisData(){

    	$actionVlue = array_values($_POST)[0];  //获取推过来的值

    	$actionName = array_keys($_POST)[0];   //获得推过来的值和要执行的方法
    	

    	$this->ajaxReturn($this->$actionName($actionVlue));	//调用对应的方法 返回对应的信息
    	   
    }

    //检测原密码
    public function oldpassword($actionValue){
    	$passwordPreg = '/\w{6}/';  //正则表达式
    	$currentpwd = M('user')->where("id = {$_SESSION['uid']}")->getField('password');
    	if($actionValue != $currentpwd){
    		$returnMsg = array(
				'error'     => 1,
				'content'   => '原密码不正确',
			);
    	}else{
    		$returnMsg = array(
				'error'     => 0,
				'content'   => '原密码正确',
			);
    	}
    	return $returnMsg;
    }

    //检测新密码
    public function newpassword($actionValue){
    	$passwordPreg = '/\w{6}/';  //正则表达式
    	//当前密码
    	$currentpwd = M('user')->where("id = '{$_SESSION['uid']}'")->getField('password');
    	if(!preg_match($passwordPreg, $actionValue)){
    		$returnMsg = array(
				'error'     => 1,
				'content'   => '密码长度不够',
			);
    	}elseif($actionValue == $currentpwd){
    		$returnMsg = array(
				'error'     => 1,
				'content'   => '密码不能与当前的相同',
			);
    	}else{
    		$_SESSION['tmppassword'] = $actionValue;  //将符合密码存起来 方便确认密码使用
    		$returnMsg = array(
				'error'     => 0,
				'content'   => '密码符合要求',
			);
    	}
    	return $returnMsg;
    }

    //检测确认密码
    public function confirmpassword($actionValue){
    	
    	if( $actionValue == $_SESSION['tmppassword'] ){
    		$returnMsg = array(
				'error'     => 0,
				'content'   => '两次密码一致',
			);
    	}else{
    		$returnMsg = array(
				'error'     => 1,
				'content'   => '两次密码不一致',
			);
    	}
    	return $returnMsg;
    }

    public function askindex(){
    	layout('layoutask');
    	$this->display();
    }

    //展示页面
    public function userask(){
    	layout('layoutask');
    	$result = M('category')->select();
    	$this->assign('categorys',$result);
    	$this->display();
    }

    //文本编辑器
    public function ueditor(){
        $data = new \Org\Util\Ueditor();
        echo $data->output();
    }

    public function savequestion(){
    	if(IS_POST){
    		$data['title'] = $_POST['title'];
    		$data['content'] = $_POST['editorValue'];
    		$data['create_time'] = time();
    		$data['uid'] = $_SESSION['uid'];
    		$category = $_POST['category'];
    		$lastid = M('question')->add($data);
    		if($lastid){
    			foreach ($category as $key => $value) {
	    			$catesql = "insert into category_question(cid,qid) values({$value} ,{$lastid})";
	    			M()->execute($catesql);  			
	    		}
	    		$this->error('提问成功',U('home/blogs/bloginfo',array('qid'=>$lastid)));
    		}
    		
    	}
    }

    // 他/我的 回答
    public function useranswer(){
  //   	if(empty($_GET['uid'])){
		// 	$this->error('非法访问',U('home/index/index'));
		// }
		// http://localhost/luntanshequ/index.php/home/user/useranswer/uid/1


		$id = $_GET['uid'];
		$userResult = M('user')->where("id = {$id}")->select();
		$sql = "select t1.*,t2.*,t2.id as qid from answer t1 left join question t2 on t1.qid = t2.id  where t1.uid = {$id} ";
		$userAnswerRes = M()->query($sql);
		$count = count($userAnswerRes);   //获得数据总数
		$Page       = new \Think\Page($count,1);// 实例化分页类 传入总记录数和每页显示的记录数
		$show       = $Page->show();//	 分页显示输出
		$sql = "select t1.*,t2.*,t2.id as qid from answer t1 left join question t2 on t1.qid = t2.id  where t1.uid = {$id} order by t2.create_time desc limit {$Page->firstRow},{$Page->listRows}";
		$userAnswerRes = M()->query($sql);
		$this->assign('Page',$show);
		$this->assign('userdata',$userResult);
		$this->assign('userAnswerRes',$userAnswerRes);
    	$this->display();
    }
}
?>